﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DataBinding
{
    public partial class CarPicker : System.Web.UI.Page
    {
        private static List<Producer> prod;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack) 
            {
                prod = new List<Producer>();
                List<Model> lada = new List<Model>();
                lada.Add(new Model(1,"lada"));
                lada.Add(new Model(1, "lada"));
                lada.Add(new Model(1, "lada"));
                List<Model> jigula = new List<Model>();
                jigula.Add(new Model(1,"jigula"));
                jigula.Add(new Model(1, "jigula"));
                jigula.Add(new Model(1, "jigula"));
                List<Model> moskvich = new List<Model>();
                moskvich.Add(new Model(1,"moskvich"));
                moskvich.Add(new Model(1, "moskvich"));
                moskvich.Add(new Model(1, "moskvich"));
   
                Producer[] toBind = new Producer[] 
                {
                    new Producer(1,"BMW",lada),
                    new Producer(2,"Mercedes",jigula),
                    new Producer (3,"Zaporojec",moskvich)
                };

                prod.AddRange(toBind);
                this.producers.DataSource = toBind;
                this.producers.DataBind();
            }
        }

        protected void producers_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selected = this.producers.SelectedValue;

            Producer p = prod.FirstOrDefault(x => x.producerName == selected);

            this.models.DataSource = p.models;
            this.models.DataBind();
        }

        protected void models_SelectedIndexChanged(object sender, EventArgs e)
        {
            string htmlNewLine = "<br />";
            StringBuilder queryResult = new StringBuilder();
            queryResult.Append(htmlNewLine);
            queryResult.Append(string.Format("Producer: {0} ", this.producers.SelectedValue));
            queryResult.Append(string.Format("Model: {0} ",this.models.SelectedValue));
            foreach (ListItem item in this.extras.Items) 
            {
                if (item.Selected == true) 
                {
                    queryResult.Append(item.Value);
                }
            }
            this.result.Text = queryResult.ToString();
        }
    }
}